package manongfanshen.memory_model.volatile_visibility;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.ThreadUtil;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author ChangLiang
 * @date 2020/3/19
 */
public class MainTestV2 {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    class ThreadA extends Thread{
        // in threadA worker memory
        AtomicBoolean isStop = new AtomicBoolean(false);

        int value = 0;

        @Override
        public void run() {
            while (!isStop.get()) {
                value++;
            }
        }
    }

    @Test
    @DisplayName("test java memory model")
    public void test(){
        ThreadA threadA = new ThreadA();
        threadA.start();
        // ensure threadA start
        ThreadUtil.sleepForMilliSeconds(200);

        // in Main thread worker memory
        // threadA worker memory cannot see this
        threadA.isStop.set(true);

        logger.info("first time value:{}", threadA.value);
        ThreadUtil.sleepForMilliSeconds(1000);
        logger.info("second time value:{}", threadA.value);

    }
}
